package com.whq.mvc.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.whq.mvc.resp.BusinessException;
import com.whq.mvc.resp.EmBusinessError;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;

public class JsonUtils {

    private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class);
    private static final ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    }

    public static <T> String toJSON(T obj) throws BusinessException {
        String jsonStr;
        try {
            jsonStr = objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            logger.error("对象转json出错", e);
            throw new BusinessException(EmBusinessError.PARSEJSON_ERROR, "json数据转换出错");
        }
        return jsonStr;
    }

    public static <T> T fromJson(String jsonStr, Class<T> type) throws BusinessException {
        T obj;
        try {
            obj = objectMapper.readValue(jsonStr, type);
        } catch (JsonProcessingException e) {
            logger.error("对象转json出错", e);
            throw new BusinessException(EmBusinessError.PARSEJSON_ERROR, "json数据转换出错");
        }
        return obj;
    }
}
